<template>
	<view class="container" v-show="isOption == 0">
		<cu-custom-self :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">
				拨号
			</block>
		</cu-custom-self>
		<view class="phone_txt">{{phoneNumber}}</view>
		
		<view class="keyboard">
			<view v-for="(item, index) in 9" :key="index+1" @click="handleKey(index + 1)" hover-class="cell-hover" hover-stay-time="150">
				<text>{{ index + 1 }}</text>
			</view>
            
			<view class="small_font_btn" @click="clear()">清空</view>
            <view @click="handleKey(0)" hover-class="cell-hover" hover-stay-time="150">
            	<text>0</text>
            </view>

			<view class="small_font_btn" @click="del()">
				<i class="iconfont" style="font-size:55rpx;">&#xe61a;</i>
			</view>
		</view>

		<view class="keyboard_btn">
			<view class="call_btn" style="background-color: #f3a200;" @click.stop="handleCallBack()">
				<i class="iconfont" style="color:#fff;font-size:50rpx;margin-top:15rpx;display: block;text-align: center;">&#xe611;</i>
				<span style="display: block;width:100%;font-size:25rpx;text-align: center;float:left;clear:both;color:#fff;">回拨</span>
			</view>
		    
		    <view class="call_btn" style="background-color: #f3a200;" @click.stop="handleCallSip()" v-if="isSip == 1 || isSip == '1'">
		    	<i class="iconfont" style="font-size:50rpx;margin-top:15rpx;display:block;text-align: center;">&#xef78;</i>
		    	<span style="display: block;width:100%;font-size:25rpx;text-align: center;clear:both;float:left;color:#fff;">SIP</span>
		    </view>
		    
		    <view class="call_btn" style="background-color: #ff0000;" @click.stop="handleCallSip()" v-if="isSip == 0 || isSip == '0'">
		    	<i class="iconfont" style="font-size:50rpx;margin-top:15rpx;display: block;text-align:center;">&#xef78;</i>
		    	<span style="display: block;width:100%;font-size:25rpx;text-align: center;clear:both;float:left;color:#fff;">未注册SIP</span>
		    </view>
		    
			<view class="call_btn" @click.stop="handleCallPhone()">
				<i class="iconfont" style="color:#fff;font-size:50rpx;margin-top:15rpx;display: block;text-align: center;">&#xe622;</i>
		        <span style="display: block;width:100%;font-size:25rpx;text-align: center;clear:both;float:left;color:#fff;">外呼</span>
			</view>
			
			<view class="call_btn" @click.stop="handleGetClip()" style="background-color: #55aaff;display: block;text-align: center;margin-top:15rpx;">
				<span style="display: block;width:100%;font-size:40rpx;margin-top:30rpx;text-align: center;clear:both;float:left;color:#fff;">粘贴</span>
			</view>
		</view>
		
		<u-modal v-model="isCalls" :show-cancel-button="true" :title-style="{fontSize:'40rpx'}" confirm-text="去开启" title="未开启通话自动录音功能无法卡外呼" @cancel="isCalls = false" @confirm="confirmOpenVoice">
		    <view class="slot-content" style="height:400rpx;">
		        <text>请自动开启通话录音功能,否则无法进行外呼并生成通话录音。以下为开启方法:</text>
		        <text>1.在手机自带拨号盘通话设置中,开启'通话自动录音'</text>
		        <text>2.在系统设置中,搜索'自动录音'或'通话设置',开启'通话自动录音'</text>
		    </view>
		</u-modal>

		<u-toast ref="uToastsCallPhone" />
	</view>
</template>

<script>
	
	import {
		mapGetters,mapState
	} from "vuex";
	
	import Tabbar from "@/pages/index/tabbar.vue"; //首页
	
	import WebSip from "@/pages/index/websip.vue";

	import {
	    changeCallNumStatus,
		getClickToDial
	} from "@/api/task.js";
    
    import {isBlackByNumber} from "@/api/index.js";
    
    import {getTime} from "@/utils/data.js";
	
	const callModule = uni.requireNativePlugin("leven-call-CallModule");
	
	export default {
		computed: {
			...mapGetters(["userInfo","callTaskTimer","callType","taskType","callTaskCountTimer","voiceServiceList","isSip","sipPhone","isShowWebSip","callStatus","websipCallStatus","callingData","currentCallType"]),
			...mapState({
				PageCur: state => state.tabbar.PageCur,
				callTaskTimer: state => state.task.callTaskTimer,
				callType: state => state.task.callType,
				callCount: state => state.task.callCount,
				taskType: state => state.task.taskType,
				callTaskCountTimer: state => state.task.callTaskCountTimer,
                sipPhone:state=>state.task.sipPhone,
                isShowWebSip:state=>state.task.isShowWebSip,
				isSip:state => state.task.isSip,
				callStatus:state=>state.task.callStatus,
				websipCallStatus:state=>state.task.websipCallStatus,
				callingData: state=>state.task.callingData,
				currentCallType:state=>state.task.currentCallType
			})
		},
		components:{
			Tabbar,
			WebSip
		},
		data() {
			return {
				phoneNumber:"",
				callLogData:{
					phone_number:'',
					start_time:'',
					end_time:'',
					type:'',
					seat_id:''
				},
				
				isOption:0,
				isAdds:0,
				handleAdd:0,
				
				phonetype:'',
				
				isCalls:false,
				
				callBackType:1, //来源类型，1：手动拨号 2：通话列表 3：定时任务 4：任务列表 5：订单列表
			};
		},
		methods: {
			//开启自动通话录音
			confirmOpenVoice() {
				callModule.toCallAutoRecorderPage(res => {
					console.log("开启通话自动录音",res);
					
					this.$console.info("开启通话自动录音",res);
				});
			},
			
			//回拨
			handleCallBack(){
				if(this.phoneNumber == ""){
					this.$refs.uToastsCallPhone.show({
						title: "请输入号码！",
						type: 'error',
						duration: '2000',
					});
				}else{
					//调用接口
					let params = {
						'company_id':this.userInfo.companyid,
						'caller':this.userInfo.seat,
						'callee':this.phoneNumber,
						'seat':this.userInfo.seat,
						'pid':this.userInfo.pid,
						'type':5
					}
                    
                    //检测是否为黑名单
                    isBlackByNumber({'cid':this.userInfo.companyid,'num':this.phoneNumber,'seat':this.userInfo.seat}).then(res=>{
                        console.log("infoself isblackbynumber res",res);
                        
                        if(res.data.data.is_black >= 1){
                            let title_str = res.data.data.is_black == 1 ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':(res.data.data.is_black == 2 ? '已开启黑名单过滤，该号码为企业黑名单，禁止外呼！':'已开启黑名单过滤，该号码为系统黑名单，禁止外呼！');
                            this.$refs.uToastsCallPhone.show({
                            	title: title_str,
                            	type: 'error',
                            	duration: '1000',
                            });
                        }else{
                            
                            //回拨，判断坐席外呼主叫号码是否存在
                            if (this.userInfo.shownum == "" || this.userInfo.shownum == '0') {
                                this.$refs.uToastsCallPhone.show({
                                    title: "请设置外呼主叫号码",
                                    type: 'error',
                                    duration: '3000',
                                });
                                return;
                            } else {
                                params.shownum = this.userInfo.shownum;
                                params.phone = params.callee;
                                params.cid = params.company_id;
                    
                                console.info("回拨--参数",params);
                                this.$console.info("回拨--参数",params);
                    
                                //先调用回拨接口，有返回结果后保存通话记录
                                getClickToDial(params).then(res => {
                                    console.log("getClickToDial res", res);
                                    this.$console.info("回拨--回拨接口成功 返回数据",res);
                                    
                                    if(res.data.code == 200){
                                        this.$refs.uToastsCallPhone.show({
                                            title: "回拨成功",
                                            type: 'success',
                                            duration: '2000',
                                        });
                                        
                                        //通话开始时间
                                        params.start_time = new Date().getTime();
                                                                    
                                        //放入全局参数
                                        // this.$globalData.callData = params;
                                        
                                        console.info("回拨--先停止定时任务 ",params.callee);
                                        this.$console.info("回拨--先停止定时任务 ",params.callee);
                                        
                                        //先清除任务
                                        clearInterval(this.$globalData.taskTimer);
                                        this.$globalData.taskTimer = null;
                                        
                                        //记录日志
                                        console.info("回拨--开始外呼 ", params.callee);
                                        this.$console.info("回拨--开始外呼 ",params.callee);
                                        
                                    }else{
                                        this.$refs.uToastsCallPhone.show({
                                            title: res.data.msg,
                                            type: 'error',
                                            duration: '3000',
                                        });
                                        
                                        console.info("回拨--回拨接口失败 返回数据 ", params.callee);
                                        this.$console.info("回拨--回拨接口失败 返回数据 ", params.callee);
                                        
                                        //开启任务定时器
                                        if(this.taskType == 0 && this.$globalData.taskTimer == null){
                                            this.$globalData.taskTimer = setInterval(()=>{
                                                uni.$emit("handleGetCall");
                                            },2000);
                                        }
                                    }
                                }).catch(err => {                            
                                    console.info("回拨--回拨接口错误 返回数据 err", params.callee,err);
                                    this.$console.info("回拨--回拨接口错误 返回数据 ", params.callee,err);
                                });
                            }
                        
                        }
                    });
                }
			},
			
            //SIP呼叫
            handleCallSip(){
                //检测是否为黑名单
                isBlackByNumber({'cid':this.userInfo.companyid,'num':this.phoneNumber,'seat':this.userInfo.seat}).then(res=>{
                    console.log("infoself isblackbynumber res",res);
                    
                    if(res.data.data.is_black >= 1){
                        let title_str = res.data.data.is_black == 1 ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':(res.data.data.is_black == 2 ? '已开启黑名单过滤，该号码为企业黑名单，禁止外呼！':'已开启黑名单过滤，该号码为系统黑名单，禁止外呼！');
                        this.$refs.uToastsCallPhone.show({
                        	title: title_str,
                        	type: 'error',
                        	duration: '1000',
                        });
                    }else{
                        
                        //if(this.isSip == 1 || this.isSip == '1'){
                            console.log("issip 1",this.isSip,this.phoneNumber);
                            
                            if(this.phoneNumber == ""){
                                this.$refs.uToastsCallPhone.show({
                                    title: "请输入号码！",
                                    type: 'error',
                                    duration: '2000',
                                });
								
								return false;
                            }else{
                                
                                this.$console.info("SIP呼叫 ",this.phoneNumber);
                            
                                this.$store.dispatch("setCallStatus",1);
                                
                                this.$store.dispatch("setCallingData",{id:'',phone:this.phoneNumber,type:'sip'});
								
								this.$store.dispatch("setSipPhone",this.phoneNumber);
								this.$store.dispatch("setIsShowWebSip",1);
								
								//WebSip.methods.handleSendMessage("phone",{"phone":this.phoneNumber});
                            }
                        // }else{
                        //     console.log("issip 0",this.isSip);
                        // }
                    }
                });
            },
            
            //直接外呼
            handleCallPhone(){
                let _this = this;
                
                //调用接口
                let params = {
                	'company_id':_this.userInfo.companyid,
                	'caller':_this.userInfo.seat,
                	'callee':_this.phoneNumber,
                	'seat':_this.userInfo.seat,
            		'type':3,
                    'pid':_this.userInfo.pid,
                    'tid':''
                }
                
                //检测是否为黑名单
                isBlackByNumber({'cid':this.userInfo.companyid,'num':params.callee,'seat':this.userInfo.seat}).then(res=>{
                    console.log("infoself isblackbynumber res",res);
                    
                    if(res.data.data.is_black >= 1){
                        let title_str = res.data.data.is_black == 1 ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':(res.data.data.is_black == 2 ? '已开启黑名单过滤，该号码为企业黑名单，禁止外呼！':'已开启黑名单过滤，该号码为系统黑名单，禁止外呼！');
                        this.$refs.uToastsCallPhone.show({
                        	title: title_str,
                        	type: 'error',
                        	duration: '1000',
                        });
                    }else{
						
						if(res.data.data.is_call == 1){
							callModule.checkCallAutoRecorder(res_module => {
								console.log("检测通话录音权限 结果",res_module);
								
								_this.$console.info("检测通话录音权限 结果",res_module);
								
								if(!res_module.data.isOpen){
									console.log("未开启自动通话录音");
									
									_this.$console.info("未开启自动通话录音");
									
									//提示，没有开启自动通话录音
									_this.isCalls = true;
									
								}else{
									_this.isCalls = false;
									_this.handleCallPhones(params);
								}
							});
						}else{
							_this.handleCallPhones(params);
						}
                
                    }
                });
            },
			
			handleCallPhones(params){
				let _this = this;
				
				console.info("拨号盘--外呼参数 ",params);
				_this.$console.info("拨号盘--外呼参数 ",params);
				
				console.info("拨号盘--先停止定时任务 ",params.callee);
				_this.$console.info("拨号盘--先停止定时任务 ",params.callee);
				
				//先清除任务
				clearInterval(_this.$globalData.taskTimer);
				_this.$globalData.taskTimer = null;
				
				//获取录音目录
				plus.io.requestFileSystem(
				    plus.io.PRIVATE_DOC, // 私有文档目录（对应 _doc 路径）
				    (fs) => {
				      // 定义目录路径（示例：在 _doc 下创建 myFolder）
				      let dirPath = 'logs';
				            
				      // 检查并创建目录
				      fs.root.getDirectory(
				        dirPath,
				        { create: true }, // 自动创建目录
				        (entry) => {
				            console.log('拨号盘--创建文件夹成功:',entry.fullPath);
				            _this.$console.info('拨号盘--创建文件夹成功:',entry.fullPath);
				            uni.setStorageSync("record_files",entry.fullPath);
				}, function(e) {
				        console.log('拨号盘--创建文件夹失败:',e.message);
				        _this.$console.info('拨号盘--创建文件夹失败:',e.message);
				    });
				}, function(e) {                    
				    console.log('拨号盘--请求文件系统失败:',e.message);
				    _this.$console.info('拨号盘--请求文件系统失败:',e.message);
				});
				        
				if(params.callee != '' && params.callee != null && params.callee != undefined){
				    
				    //提前修改号码状态                    
				    changeCallNumStatus(params).then(res=>{
				        //通话状态监听
				        params.start_time = getTime();
				        
				        console.info("拨号盘--接口修改号码状态 成功",params.callee,res);
				        _this.$console.info("拨号盘--接口修改号码状态 成功",params.callee,res);
				        
				        //记录日志
				        console.info("拨号盘--开始外呼 ",params.callee);
				        _this.$console.info("拨号盘--开始外呼 ",params.callee);
				        
				        //放入全局参数
				        _this.$globalData.callData.push(params);
						
						//启动通话状态监听
						if(_this.$globalData.callStatusTimer == null){
							_this.$globalData.callStatusTimer = setInterval(()=>{
								uni.$emit("handleRegisterListener");
							},500);
						}
				    
				        //自动拨号
				        plus.device.dial(params.callee,false);
					
				        
				        // // 导入Activity、Intent类  
				        // let Intent = plus.android.importClass("android.content.Intent");
				        // let Uri = plus.android.importClass("android.net.Uri");
				        // // 获取主Activity对象的实例  
				        // let main = plus.android.runtimeMainActivity();
				        // // 创建Intent  
				        // let uri = Uri.parse(`tel:${params.callee}`); // 这里可修改电话号码  
				        // let call = new Intent("android.intent.action.CALL", uri);
				        // // 调用startActivity方法拨打电话  
				        // main.startActivity(call);
				        
				        console.log('外呼，完成');
				        _this.$console.info("拨号盘--转到手机系统外呼 ",params);
						
						setTimeout(()=>{
							uni.navigateBack({
								delta: 1
							});
						},500);
				    }).catch(err=>{
				        console.info("拨号盘--接口修改号码状态 失败 err"+params.callee,err);
				        _this.$console.info("拨号盘--接口修改号码状态 失败 err "+params.callee,err);
				        
				        //开启任务定时器
				        if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
				            _this.$globalData.taskTimer = setInterval(()=>{
				                uni.$emit("handleGetCall");
				            },2000);
				        }
				    });
				}else{
				    _this.$console.info("拨号盘--号码为空 ",params);
				    
				    //开启任务定时器
				    if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
				        _this.$globalData.taskTimer = setInterval(()=>{
				            uni.$emit("handleGetCall");
				        },2000);
				    }
				}
				
			},
            
            // 键盘
			handleKey(e){
				// console.log("key",e);
				// console.log("phone ss",this.phoneNumber);
				if(this.phoneNumber == '' || this.phoneNumber == undefined){
					this.phoneNumber = e+'';
				}else{
					this.phoneNumber += e+'';
				}
				
				//console.log("phone",this.phoneNumber);
			},
			
			//读取剪贴板
			handleGetClip(){
				
				let Context = plus.android.importClass("android.content.Context");  
				let main = plus.android.runtimeMainActivity();  
				let clip = main.getSystemService(Context.CLIPBOARD_SERVICE);  
				let clip_text = plus.android.invoke(clip,"getText");
				
				console.log("context",Context,clip,clip_text);
				
				if(clip_text && this.isValidPhoneNumber(clip_text)){
				
					this.phoneNumber = clip_text;
				}
			},
			
			//固话，手机号码检查函数
			isValidPhoneNumber(phoneNumber) {
			    // 去除任何非数字字符
			    const cleaned = phoneNumber.replace(/\D/g, '');
			 
			    // 定义正则表达式验证规则
			    const mobilePattern = /^1[3-9]\d{9}$/;
			    const landlinePattern = /^0\d{2,3}-?\d{7,8}$/;
			 
			    // 验证是否符合手机号码或座机号码格式
			    if (mobilePattern.test(cleaned) || landlinePattern.test(cleaned)) {
			        return true;
			    } else {
			        return false;
			    }
			},
			
			//固话，手机号码检查函数，合法返回true,反之,返回false
			isTelephone(obj){
				let pattern=/(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^[0−9]3,4[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/;
				if(pattern.test(obj)){
					return true;
				}else{
					return false;
				}
			},
			
			//清空输入内容
			clear(){
				this.phoneNumber = "";
			},
			
			//从末尾删除一位
			del() {
				if (this.phoneNumber.length > 0) {
					this.phoneNumber = this.phoneNumber.substring(0, this.phoneNumber.length - 1)
				}
			}
        },
		onReady() {
			
		},
		onShow() {
			console.log("callphone onshow");
			// this.$nextTick(()=>{
				
			// 	this.$refs.uToastsCallPhone.show({
			// 	    title: "绑定号码有误或余额不足",
			// 	    type: 'error',
			// 	    duration: '3000',
			// 	});
				
			// });
		},
		onLoad(options) {
			uni.hideTabBar(); //不让底部显示tab选项
		
		},
		destroyed() {
			this.callBackType = 1;
		}
	}
</script>

<style lang="scss">
	.container {
		width: 100%;
		color: #333333;
		background-image: linear-gradient(to bottom, #075AFF, #ffffff);
		background-size: 100% 45%;
		background-repeat: no-repeat;
		background-position: top center;
		overflow-y: scroll;
	}
.phone_txt{
	font-size:60rpx;
	text-align: center;
	background-color:unset;
	margin-top:20%;
	width:96%;
	margin-left:2%;
	color: #000;
	font-weight:bold;
}

.keyboard {
	position: fixed;
	bottom: 18%;
	width: 80%;
	margin-left:10%;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;

	view {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 150rpx;
		height:150rpx;
		background: #dcdcdc;
		border-radius: 75rpx;
		margin-top: 20rpx;
		font-size: 50rpx;
		font-weight: bold;
		margin-left:15rpx;
		margin-right:15rpx;
	
	}
	
	.cell-hover{
		background: #eee;
	}
	
	.call_btn{
		background:#49dd6c;
		font-size:40rpx;
	}
	
	.call_btn .iconfont{
		color:#fff;
		font-size:80rpx;
	}
	
	.del_btn{
		background:unset;
		text-align: center;
	}
	
	.del_btn .iconfont{
		font-size:60rpx;
		color:#bdbdbd;
	}
	
	.clear_btn{
		background:unset;
		font-size:30rpx;
		color:#004fef;
		text-align: center;
	}
	
	.small_font_btn{
		font-size:35rpx;
	}
}

.keyboard_btn {
	position: fixed;
	bottom: 8%;
	width: 80%;
    height:120rpx;
	margin-left:10%;
	// display: flex;
	// flex-wrap: wrap;
	// justify-content: space-between;

	view {
		// display: flex;
		// align-items: center;
		// justify-content: center;
        margin:0 auto;
        float:left;
		width: 120rpx;
		height:120rpx;
		background: #dcdcdc;
		border-radius: 60rpx;
		margin-top: 20rpx;
		font-size: 50rpx;
		font-weight: bold;
		margin-left:15rpx;
		margin-right:15rpx;
	
	}
	
	.cell-hover{
		background: #eee;
	}
	
	.call_btn{
		background:#49dd6c;
		font-size:40rpx;
	}
	
	.call_btn .iconfont{
		color:#fff;
		font-size:80rpx;
	}
	
	.del_btn{
		background:unset;
		text-align: center;
	}
	
	.del_btn .iconfont{
		font-size:60rpx;
		color:#bdbdbd;
	}
	
	.clear_btn{
		background:unset;
		font-size:30rpx;
		color:#004fef;
		text-align: center;
	}
	
	.small_font_btn{
		font-size:35rpx;
	}
}

</style>